package com.boot2.core.web.filter;

import com.boot2.core.dao.i.MsTokenDao;
import com.boot2.core.exception.BusinessException;
import com.boot2.core.model.MsToken;
import com.boot2.core.utils.ServletUtil;
import com.boot2.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangweilin
 * @description: 微服务的身份认证
 * @date 2018/9/30
 */
//@Component
public class MsJwtAuthenticationFilter extends JwtAuthenticationFilter {

//    @Autowired
//    Environment environment;

    @Autowired
    MsTokenDao msTokenDao;

    public MsJwtAuthenticationFilter() {

    }

    /**
     * 提供一个手工实例化的入口
     * @param msTokenDao
     */
    public MsJwtAuthenticationFilter(MsTokenDao msTokenDao) {
        this.msTokenDao = msTokenDao;
        init();
    }

    /**
     * 当前全部服务集合
     */
    private List<MsToken> tokenList;
    private Map<String, String> tokenMap;

    @PostConstruct
    public void init() {
//        String property = environment.getProperty("spring.application.name");
//        if (StringUtils.isEmpty(property)) {
//            throw new BusinessException("spring.application.name can not be null");
//        }
//        MsToken msToken = msTokenDao.findOneByServiceName(property);
//        if (null == msToken) {
//            throw new BusinessException("当前服务没有配置token");
//
//        }

        List<MsToken> tokenList = msTokenDao.findAll();
        if (CollectionUtils.isEmpty(tokenList)) {
            throw new BusinessException("未配置微服务token数据库");
        }
        tokenMap = new HashMap<>();
        for (MsToken msToken : tokenList) {
            tokenMap.put(msToken.getToken(), msToken.getServiceName());
        }
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //先验证一下微服务的请求，如果微服务不需要校验，则走账号登录的jwt token校验
        String token = ServletUtil.getRequestToken(request);
        if (StringUtils.isNotEmpty(token)) {
            if (tokenMap.containsKey(token)) {
                String serviceName = tokenMap.get(token);
                System.out.println("通过【"+serviceName+"】微服务请求...");
                filterChain.doFilter(request, response);
                return;
            }
        }
        super.doFilterInternal(request, response, filterChain);
    }
}
